package com.fingard.dsp.bank.directbank.zjrc01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.updownfile.DownFileHelper;
import com.fingard.dsp.bank.dbobj.updownfile.DownFileRecord;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.directbank.boc01.receiptpro.BOC01TaskReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.*;
import java.util.*;

/**
 * 浙江农信电子回单查询
 */
public class ZJRC01ReceiptPro extends ZJRC01Base implements IReceiptPro {

    @Override
    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        StringBuilder sbd=new StringBuilder();//处理失败记录
        int count=0;//总查询回单数
        int downloadCount=0;//已入库的回单数
        int refCount=0;//已重复的回单数
        //1、银企电子回单查询列表
        List<String> receiptList=new ArrayList<String>();
        //因为ATS查询回单为全部类型，银行不支持查询全部类型，改为配置的方式支持
        String[] typeArr=null;
        if(StringHelper.hasAnyChar(getBankConfig().getValueAsString("receiptFlag"))){
            typeArr=getBankConfig().getValueAsString("receiptFlag").split(",");
        }else {
            typeArr=new String[]{"1","2"};
        }
        for(String type:typeArr){//回单标志 1-入账电子回单  2-扣款电子回单
            List<String[]> receiptTypeAryAll=getAllReceiptType();//获取全部列举的回单组合
            for(String[] receiptTypeAry:receiptTypeAryAll){
                WriteBankLogLn("查询"+pReqReceipt.actNum+"回单类型："+receiptTypeAry[0]+"业务类型："+receiptTypeAry[1]+"回单标志："+("1".equals(type)?"入账电子回单":"扣款电子回单"));
                String tellerSeqNo="";
                String subTranFlow="";
                String date="";
                String resultFlag="";
                while (StringHelper.isNullOrEmpty(resultFlag) || "0".equals(resultFlag)){
                    //组装请求报文
                    tranCode = "100025";
                    serialNo = getQryTransID();
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeElementString("warrantType",receiptTypeAry[0],true);//回单类型
                    xmlWriter.writeElementString("warrantSign",type,true);//回单标志1入账2出账
                    xmlWriter.writeElementString("businessType",receiptTypeAry[1],true);//业务类型
                    xmlWriter.writeElementString("accountNo",pReqReceipt.actNum,true);//帐号
                    xmlWriter.writeElementString("beginDate",Format.Date8Format.format(pOneDay),true);//起始日期
                    xmlWriter.writeElementString("endDate",Format.Date8Format.format(pOneDay),true);//终止日期
                    xmlWriter.writeElementString("tellerSeqNo",tellerSeqNo,true);//柜员流水号
                    xmlWriter.writeElementString("subTranFlow",subTranFlow,true);//子交易流水号
                    xmlWriter.writeElementString("date",date,true);//再次定位的日期
                    xmlWriter.writeEndDocument();
                    //请求报文至银行并接收响应
                    Thread.sleep(sleepTime(tranCode));
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    //处理响应报文
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        int index = tmpStrRet[1].indexOf("</ebank>");
                        if(index>0){
                            tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmpStatus = tmpBkReader.getFirstTextNotNull("/ebank/resHead/retCode");
                                String tmpStatusText = tmpBkReader.getFirstTextNotNull("/ebank/resHead/errMsg");
                                if (tmpStatus != null && isActiveRetCode(tmpStatus)) {
                                    resultFlag=tmpBkReader.getFirstTextNotNull("/ebank/resBody/flag").trim();
                                    if(!"0".equals(resultFlag) && !"1".equals(resultFlag)){
                                        break;
                                    }
                                    if("0".equals(resultFlag)){
                                        tellerSeqNo=tmpBkReader.getFirstTextNotNull("/ebank/resBody/tellerSeqNo").trim();
                                        subTranFlow=tmpBkReader.getFirstTextNotNull("/ebank/resBody/subTranFlow").trim();
                                        date=tmpBkReader.getFirstTextNotNull("/ebank/resBody/date");
                                    }
                                    while (tmpBkReader.read("/ebank/resBody/yqElecWarrantList/row")){
                                        String key=tmpBkReader.readedXElement.getSingleTextNotNull("tellerSeqNo").trim() +"_"
                                                +tmpBkReader.readedXElement.getSingleTextNotNull("subTranFlow").trim() +"_"
                                                +tmpBkReader.readedXElement.getSingleTextNotNull("transferTime").trim() + "_"
                                                +receiptTypeAry[0]+"_"+type+"_"+tmpBkReader.readedXElement.getSingleTextNotNull("currencyType").trim();
                                        receiptList.add(key);
                                        count++;
                                    }
                                } else {
                                    WriteBankLogLn(tmpStatusText);
                                    break;
                                }
                            } else {
                                WriteBankLogLn(tmpSbMsg.toString());
                                break;
                            }
                        }else {
                            WriteBankLogLn(tmpStrRet[1]);
                            break;
                        }
                    } else {
                        WriteBankLogLn(tmpStrRet[1]);
                        break;
                    }
                }
            }
        }
        WriteBankLogLn("****************共成功查询到"+count+"条回单****************");
        //2、银企电子回单详情
        if(receiptList!=null && receiptList.size()>0){
            for (String receiptName : receiptList){
                WriteBankLogLn("查询回单"+receiptName+"详情数据");
                String[] context=receiptName.split("_");//柜员流水号_子流水号_时间_回单类型_借贷标识(1入账2出账)_币种
                //String receiptType=entry.getValue();//回单类型
                //生成html文件
                String receiptHtmlName=receiptName+".html";//回单html名称
                String receiptMainDir=FGBiz.dspCenter.dspSet.receiptMainDir+File.separator+Format.Date8Format.format(pOneDay)
                        +File.separator+pReqReceipt.actNum+File.separator+receiptHtmlName;//本地临时html存储路径
                /*if(FileHelper.existFile(receiptMainDir)){
                    WriteBankLogLn("回单"+receiptMainDir+"数据已存在");
                    refCount++;
                    continue;
                }*/
                //组装请求报文
                tranCode = "100024";
                serialNo = getQryTransID();
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter);
                xmlWriter.writeElementString("warrantType",context[3],true);//回单类型
                xmlWriter.writeStartElement("yqElecWarrantFlowNoList");
                xmlWriter.writeStartElement("row");
                xmlWriter.writeElementString("tellerSeqNo",context[0],true);//柜员流水号
                xmlWriter.writeElementString("subTranFlow",context[1],true);//子流水号
                xmlWriter.writeElementString("date",context[2],true);//日期
                xmlWriter.writeElementString("standby","",true);//备用
                xmlWriter.writeEndDocument();
                //请求报文至银行并接收响应
                Thread.sleep(sleepTime(tranCode));
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    if(tmpStrRet[1].indexOf("<html")>-1 || tmpStrRet[1].indexOf("</html>")>-1){
                        String resultHtml=tmpStrRet[1].replaceAll("<span>","").replaceAll("</span>","");
                        Document receiptDoc = (Document) Jsoup.parse(resultHtml);
                        Element receiptNoTable = receiptDoc.select("#tradeDetailTab").last();//获取
                        if(receiptNoTable!=null){
                            //html格式调整
                            String receiptHtml=tmpStrRet[1].replaceAll("&nbsp;"," ").replaceAll("nbsp"," ");
                            String headOn=receiptHtml.substring(0,receiptHtml.indexOf("</head>"));
                            String headDown=receiptHtml.substring(receiptHtml.indexOf("</head>"));
                            receiptHtml=headOn+htmlCSS+headDown;//引入css
                            receiptHtml=getHtmlContent(receiptHtml);//调整html内容
                            //写入文件
                            FileHelper.writeFile(receiptMainDir,receiptHtml,getCharset());
                            //记录下载数据
                            if(FileHelper.existFile(receiptMainDir)){
                                DownFileRecord downRd = new DownFileRecord();
                                downRd.srcSys = this.bankFront.bankCode;
                                downRd.bank = banks;
                                downRd.bankFrontCode = this.bankFront.code;
                                downRd.busDate = Integer.parseInt(Format.Date8Format.format(pOneDay));
                                downRd.downState = "1";
                                downRd.filePath = receiptMainDir;
                                downRd.ownAct = pReqReceipt.actNum;
                                DownFileHelper dHelper = null;
                                try{
                                    Date nowDay = new Date();
                                    //此时采用当日，记录待下载文件，通过计划任务运行下载
                                    dHelper = new DownFileHelper(pReqReceipt.reqHeader.tenant, nowDay);
                                    int rowsAff = dHelper.insertIfNotExist(downRd);
                                    String aLog = "写入文件下载记录表行数："+rowsAff;
                                    if(rowsAff == 1){
                                        downloadCount++;
                                        aLog += "，记录写入成功";
                                        BOC01TaskReceiptPro.resetDelayCounter();
                                    }else if(rowsAff == 0){
                                        aLog += "，记录已存在";
                                        refCount++;
                                    }
                                    WriteBankLogLn(aLog);
                                }catch(Exception ex){
                                    WriteBankLogLn(ex);
                                }finally{
                                    if(dHelper!=null){
                                        dHelper.close();
                                    }
                                }
                            }
                        }else {
                            //WriteBankLogLn("返回数据"+tmpStrRet[1]+"不是回单数据");
                            sbd.append("返回数据异常："+tmpStrRet[1]+"\n");
                        }
                    }else {
                        sbd.append("返回数据异常："+tmpStrRet[1]+"\n");
                        //WriteBankLogLn("返回数据"+tmpStrRet[1]+"异常");
                    }
                }else {
                    sbd.append("返回数据异常："+tmpStrRet[1]+"\n");
                    //WriteBankLogLn(tmpStrRet[1]);
                }
            }
        }
        WriteBankLogLn("查询总数："+count+"；已处理数据："+(downloadCount+refCount));
        WriteBankLogLn("异常数据日志：\n"+sbd.toString());
        return null;
    }
}